import 'dart:async';
import 'dart:convert';
import 'package:du_application/http/HttpUtil.dart';
import 'package:du_application/model/IndexModel.dart';
import 'package:du_application/model/ListModel.dart';
import 'package:du_application/pages/GoodsCards.dart';

import 'package:du_application/provide/ListProvider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provide/provide.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';


class SeachPage extends StatelessWidget {
 final String id;
 final String title;
  const SeachPage({Key key,this.id,this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
       return Provide<ListProvider>(
        builder: (context,child,index){
             return index==null||index.model==null||index.model.data.firstList==null?_loadingContainer:ListV(list:index.model.data.firstList,id:id,pages:index.model.data.pages);
        });
  }
}
class ListV extends StatefulWidget {
  List<GoodsList> list;
    int  offset=2;
    String id;
    int pages;
  ListV({Key key,this.list,this.id,this.pages}) : super(key: key);

  @override
  _ListVState createState() => _ListVState();
}

class _ListVState extends State<ListV> {

  @override
  void initState() {


    super.initState();
  }
   
  @override
  Widget build(BuildContext context) {
      List<GoodsList> list;
  ScrollController _scrollController;
  RefreshController _refreshController;
  int  offset;
  String id;
  int pages;
setState(() {
   list=widget.list;
   offset=widget.offset;
   id=widget.id;
   pages=widget.pages;
   _scrollController=ScrollController();
   _refreshController=RefreshController(initialRefresh: true);
});
   void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
   try{
  
if(offset>pages){
    _refreshController.loadNoData();
    return;
}
   await HttpUtil.getInstance().get("/goods/list?categoryId=${id}&offset=${offset}").then((data) {
      ListModel model = ListModel.fromJson(json.decode(data.toString()));

      if(offset>model.data.pages){
        setState(() {
             _refreshController.loadNoData();
        });
     
         return;
      }
      this.setState(() {
          list.addAll(model.data.firstList.toList());
          widget.offset=offset+1;
       
      });
    
    });
   }catch(e){
     _refreshController.loadFailed();
   }
 
    

  }
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 10,
        centerTitle: true,
        title: Text(""),
        actions: <Widget>[
          Container(
            // margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
            padding: EdgeInsets.only(right: 10, top: 3),
            child: Center(
              child: Icon(Icons.share),
            ),
          )
        ],
      ),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        // WaterDropHeader、ClassicHeader、CustomHeader、LinkHeader、MaterialClassicHeader、WaterDropMaterialHeader
        header: ClassicHeader(
//          height: 45.0,
         releaseText: '松开手刷新',
         refreshingText: '刷新中',
         completeText: '刷新完成',
         failedText: '刷新失败',
         idleText: '下拉刷新',
        ),

        // ClassicFooter、CustomFooter、LinkFooter、LoadIndicator
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("下拉加载");
            }
            else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            }
            else if (mode == LoadStatus.failed) {
              body = Text("请求失败,请重试");
            }
            else {
              body = Text("没有数据啦");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child:Container(
            margin: EdgeInsets.only(bottom: 1),
            decoration: BoxDecoration(
              color: Color.fromRGBO(255, 255, 255, 1),
            ),
            child: GridView.builder(
              controller: _scrollController,
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  //横轴元素个数
                  crossAxisCount: 2,
                  //纵轴间距
                  mainAxisSpacing: 1.0,
                  //横轴间距
                  crossAxisSpacing: 1.0,
                  //子组件宽高长度比例
                  childAspectRatio: 1.0),
              itemBuilder: (context, item) {

                return getGoodCard(context,list[item]);
              },
              itemCount: list.length,
            ),
          )));
    
  }
}


   final _loadingContainer = Container(
      width: ScreenUtil().setHeight(1080),
      height: ScreenUtil().setHeight(1920),
      constraints: BoxConstraints.expand(),
      color: Colors.black,
      child: Center(
        child: Opacity(
          opacity: 0.9,
          child: SpinKitWave(
            color: Colors.white,
            size: 50.0,
          ),
        ),
      ));
